<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { User, Tools, Odometer, Location, Timer, Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { ElMessage } from 'element-plus'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'

const router = useRouter()
const userStore = useUserStore()

// 系统概览数据
const systemStats = ref({
  totalUsers: 0,
  totalMaintainers: 0,
  totalAdmins: 0,
  totalTasks: 0,
  completedTasks: 0,
  pendingTasks: 0
})

// 最近养护任务
const recentTasks = ref([])

// 养护人员列表
const maintainers = ref([])

// 加载系统数据
const loadSystemData = async () => {
  try {
    // 获取用户统计
    const allUsers = userStore.getAllUsers()
    systemStats.value.totalUsers = allUsers.length
    systemStats.value.totalMaintainers = allUsers.filter(u => u.role === 'maintainer').length
    systemStats.value.totalAdmins = allUsers.filter(u => u.role === 'admin').length

    // 获取养护人员列表
    maintainers.value = userStore.getMaintainers()

    // 已删除车辆数据

    // 加载道路损坏数据统计
    await loadRoadDamageStats()
  } catch (error) {
    console.error('加载系统数据失败', error)
    ElMessage.error('加载系统数据失败')
  }
}

// 加载道路损坏数据统计
const loadRoadDamageStats = async () => {
  try {
    // 创建道路损坏要素图层
    const roadDamageLayer = new FeatureLayer({
      url: 'https://services7.arcgis.com/gcgG56UMRGbwuqfF/arcgis/rest/services/RoadDamageSegment/FeatureServer/0',
      outFields: ['*']
    })

    // 查询所有道路损坏数据
    const query = roadDamageLayer.createQuery()
    query.where = "1=1"
    query.outFields = ["*"]
    query.returnGeometry = false

    const results = await roadDamageLayer.queryFeatures(query)
    const features = results.features

    // 更新统计数据
    systemStats.value.totalTasks = features.length
    systemStats.value.completedTasks = features.filter(f => f.attributes.status === '已完成').length
    systemStats.value.pendingTasks = features.filter(f => f.attributes.status !== '已完成').length

    // 获取最近的5个任务
    const sortedFeatures = [...features].sort((a, b) => {
      const dateA = a.attributes.reportTime ? new Date(a.attributes.reportTime).getTime() : 0
      const dateB = b.attributes.reportTime ? new Date(b.attributes.reportTime).getTime() : 0
      return dateB - dateA // 降序排列，最新的在前面
    }).slice(0, 5)

    // 转换为任务列表格式
    recentTasks.value = sortedFeatures.map(feature => {
      const status = feature.attributes.status === '待处理' ? 'pending' :
                    feature.attributes.status === '处理中' ? 'in-progress' :
                    feature.attributes.status === '已完成' ? 'completed' : 'pending'

      return {
        id: feature.attributes.OBJECTID,
        title: feature.attributes.damageType || '道路损坏',
        location: feature.attributes.roadName || '未知位置',
        assignee: feature.attributes.maintainer || '未分配',
        status: status,
        completedDate: feature.attributes.maintainTime || null
      }
    })
  } catch (error) {
    console.error('加载道路损坏数据统计失败', error)
    ElMessage.error('加载道路损坏数据统计失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadSystemData()
})

// 获取任务状态对应的标签类型和文本
const getStatusInfo = (status: string) => {
  switch (status) {
    case 'pending':
      return { type: 'info', text: '待处理' }
    case 'in-progress':
      return { type: 'warning', text: '进行中' }
    case 'completed':
      return { type: 'success', text: '已完成' }
    default:
      return { type: '', text: '' }
  }
}

// 已删除月度任务统计相关代码
</script>

<template>
  <div class="admin-container">
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><User /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ systemStats.totalMaintainers }}</div>
              <div class="stat-label">养护人员数量</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><Tools /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ systemStats.pendingTasks }}</div>
              <div class="stat-label">待处理任务</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <el-icon><Odometer /></el-icon>
            <div class="stat-info">
              <div class="stat-value">{{ systemStats.completedTasks }}</div>
              <div class="stat-label">已完成任务</div>
            </div>
          </div>
        </el-card>
      </el-col>


    </el-row>

    <!-- 快速操作按钮 -->
    <el-row :gutter="20" class="action-row">
      <el-col :span="24">
        <el-card class="action-card">
          <div class="action-buttons">
            <el-button type="primary" @click="router.push('/admin/road-damage')">
              <el-icon><Warning /></el-icon> 道路损坏管理
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="main-row">
      <el-col :span="16">


        <el-card class="task-list-card">
          <template #header>
            <div class="card-header">
              <el-icon><Tools /></el-icon>
              <span>最近养护任务</span>
            </div>
          </template>

          <el-table :data="recentTasks" style="width: 100%">
            <el-table-column prop="id" label="任务ID" width="80" />
            <el-table-column prop="title" label="任务名称" width="150" />
            <el-table-column prop="location" label="位置">
              <template #default="scope">
                <div class="location-cell">
                  <el-icon><Location /></el-icon>
                  <span>{{ scope.row.location }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="assignee" label="负责人" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusInfo(scope.row.status).type" size="small">
                  {{ getStatusInfo(scope.row.status).text }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="completedDate" label="完成日期" width="120">
              <template #default="scope">
                <div v-if="scope.row.completedDate" class="date-cell">
                  <el-icon><Timer /></el-icon>
                  <span>{{ scope.row.completedDate }}</span>
                </div>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default>
                <el-button size="small" type="primary" plain>查看</el-button>
                <el-button size="small" type="info" plain>编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <el-col :span="8">


        <el-card class="maintainer-list-card">
          <template #header>
            <div class="card-header">
              <el-icon><User /></el-icon>
              <span>养护人员列表</span>
            </div>
          </template>

          <el-table :data="maintainers" style="width: 100%">
            <el-table-column prop="name" label="姓名" width="80" />
            <el-table-column prop="role" label="职位" />
            <el-table-column prop="tasks" label="任务数" width="80" />
            <el-table-column prop="active" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.active ? 'success' : 'info'" size="small">
                  {{ scope.row.active ? '在岗' : '休假' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default>
                <el-button size="small" type="primary" plain>详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.admin-container {
  padding: 10px;
}

.stats-row {
  margin-bottom: 20px;
}

.action-row {
  margin-bottom: 20px;
}

.action-card {
  padding: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.main-row {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stat-content .el-icon {
  font-size: 40px;
  color: #409EFF;
  margin-right: 15px;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 10px;
  font-size: 18px;
}

/* 已删除图表相关样式 */

.task-list-card {
  margin-bottom: 20px;
}

/* 已删除地图相关样式 */

.maintainer-list-card {
  margin-bottom: 20px;
}

.location-cell, .date-cell {
  display: flex;
  align-items: center;
}

.location-cell .el-icon, .date-cell .el-icon {
  margin-right: 5px;
  font-size: 14px;
}
</style>
